<template>
  <div class="app-container">
    <el-form :model="param" :inline="true" label-width="68px">
      <el-form-item style="width:400px"> 
        <InputBox :title="'出发/到达城市'" :inputVal1="param.boxStartCity" :inputVal2="param.boxBackCity" :inputBoxConfig="inputBoxConfig"  @inputChange="inputChange"></InputBox>
      </el-form-item>
      <el-form-item style="width:240px">
        <div>创建日期</div>
        <el-date-picker v-model="param.createDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <!-- <el-form-item style="width:300px">
        <div>带箱人</div>
        <el-input v-model="param.personBox"></el-input>
      </el-form-item> -->
      <el-form-item style="width:300px">
        <div>编号</div>
        <el-input v-model="param.releaseNo"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Refresh" @click="handleReSet" style="margin-top: 30px">重置</el-button>
        <el-button :icon="Search" type="primary" @click="getTableData" style="margin-top: 30px">搜索</el-button>
      </el-form-item>
    </el-form>

    <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange"
      style="float: left;"></cz-tages>
    <span style="margin-top: -40px;float: right;">
      <el-button :icon="Delete" type="danger" size="small" round @click="isDelete($event, 'pitch')"
        plain>批量删除</el-button>
      <el-button :icon="Upload" type="primary" size="small" round @click="boxPublish($event, 'pitch')"
        plain>批量上架</el-button>
      <el-button :icon="Download" type="info" size="small" round @click="boxDown($event, 'pitch')"
        plain>批量下架</el-button>
      <el-button :icon="Promotion" type="success" size="small" round @click="activEdit({})" plain>发布</el-button>
    </span>

    <Table ref="tableRef" v-bind="table" @pageChange="onTablePageChange" :disableHeaderCheckbox="false" @showInfo="showInfo" @activEdit="activEdit" @boxPublish="boxPublish"
      @boxDown="boxDown" @isDelete="isDelete">
    </Table>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" title="系统提示" width="500">
      <span>确认删除？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="activDelete">是的</el-button>
          <el-button type="primary" @click="param.dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
// import { statusCount, publishPitch, downPitch, deletePitch } from '@/api/boxRent'
import { getBoxEastSelfTable, statusCount, offShelf, onShelf, deletePitch } from '@/api/boxCallBack'
import citySelect from '@/components/citySelect'
import orderInfo from '@/store/modules/order'
import InputBox from '@/components/inputBox'
import { computed, onActivated, onMounted, reactive, ref } from 'vue';
import {
  Plus,
  Delete,
  Promotion,
  Edit,
  Message,
  Download,
  Upload
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const param = reactive({
  loading: false,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  stateFilter: { 5: '出租中', 10: '仓库中', 15: '待发布' },
  stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提(次新或者适货)', },
    { value: '5', label: '全新', },
  ],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  returnCityIds: [],
  carryCityIds: [],
  boxBackCity: [],
  boxStartCity: [],
  startCityOptions: [],
  backCityOptions: [],
  typeList: [],
  releaseNo:'',
  personBox:''
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'releaseNo', colWidth: '150', title: '编号', type: '<change>', command: 'showInfo', isCheck: true },
    { key: 'id', colWidth: '460', title: '出发/到达城市', type: 'hdCity', isCheck: true, isHuidiao: true },
    { key: 'boxUsagePeriod', colWidth: '80', title: '箱使期', type: 'add', after: '天', isCheck: true },
    // { key: 'minUnitPrice', colWidth: '120', title: '箱贴价格', type: 'add', before: '￥', isCheck: true },
    // { key: 'totalInventoryQty', colWidth: '120', title: '回调箱量', type: 'text', isCheck: true },
    { key: 'totalInventoryQty', colWidth: '80', title: '库存', type: 'text',isTooltip: true,tooltip: "回调箱库存是实际发布的回调箱数量", isCheck: true },
    { key: 'totalRentQty', colWidth: '150', title: '累计回调量', isTooltip: true, tooltip: "箱回调需求自发布上架以来，回调成功的订单的集装箱总数（不含回调中/回调后退款成功的订单）", sortable: true, type: 'text', isCheck: true },
    { key: 'total30RentQty', colWidth: '150', title: '30天回调量', isTooltip: true, tooltip: "计算近30天的回调箱量，回调箱量数据有1天延迟", sortable: true, type: 'text', isCheck: true },
    { key: 'status', colWidth: '80', title: '发布状态', type: 'filter', filter: param.stateFilter, cFilter: param.stateColor, isCheck: true },
    { key: 'createTime', colWidth: '150', title: '创建日期', sortable: true, type: 'dateTime', isCheck: true },
    {
      key: 'operate',
      colWidth: '200',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // content: '编辑',
          // icon: 'Edit',
          command: 'activEdit',
          name:'编辑',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },
        {
          // content: '下架',
          // icon: 'Download',
          command: 'boxDown',
          name:'下架',
          isShow: (row: { status: string; }) => {
            return row.status == '5';
          },
        },
        {
          // content: '上架',
          // icon: 'Upload',
          command: 'boxPublish',
          name:'上架',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },
        {
          // content: '删除',
          // icon: 'Delete',
          command: 'isDelete',
          name:'删除',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },

      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

onActivated(() => {
  getTableData()
});

const startCityId = (id: string) => {
  param.carryCityIds = id
}
const backCityId = (id: string) => {
  param.returnCityIds = id
}

function handleTypeChange(val: any) {
  console.log(val)
  param.status = val
  getTableData()
}

//重置
function handleReSet() {
  param.boxStartCity = null
  param.boxBackCity = null
  param.releaseNo = null
  param.personBox = null
  param.beginTotalRentQty = ""
  param.endTotalRentQty = ""

  getTableData()
}

function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    carryCityIds: param.boxStartCity,
    returnCityIds: param.boxBackCity,
    beginTotalRentQty: param.beginTotalRentQty - 0 || "",
    endTotalRentQty: param.endTotalRentQty - 0 || "",
    status: param.status - 0 || null,
    releaseNo:param.releaseNo?.trim(),
    personBox:param.personBox?.trim()
  };
  if (param.createDate) {
    data.beginCreateDate = param.createDate[0];
    data.endCreateDate = param.createDate[1];
  }
  table.config.loading = true;
  // 获取列表数据
  getBoxEastSelfTable(data).then((res: any) => {
    const list = JSON.parse(JSON.stringify(res.data.list));
    formatCityInfo(list)
    table.data = list
    table.config.total = res.data.total;
  });
  statusCount(data).then((res: { data: any }) => {
    const resList = res.data // [ { status: 5, totalQty: 0 },{ status: 10, totalQty: 0 },{ status: 15, totalQty: 0 } ]
    const list = [{ id: 0, name: '全部', num: 0 }, { id: 5, name: '出租', num: 0 }, { id: 10, name: '仓库中', num: 0 }, { id: 15, name: '待发布', num: 0 }]
    param.typeList = formatStateCount(list, resList)
    table.config.loading = false;
  })
  table.config.loading = false;
}


//编辑
const router = useRouter();
const activEdit = (row: any) => {
  if (row) {
    orderInfo().setRowData(row)
  }
  router.push({ // type:hd 货代发布回调箱  type:xd 集装箱公司发布回调箱
    path: 'publish',
    query: { 
      type:'xd' 
    }
  })
};
//详情
const showInfo = (row: any) => {
  row.isInfo=true
  if (row) {
    orderInfo().setRowData(row)
  }
  router.push({
    path: 'publish',
    query: {
      type:'xd'
    }
  })
};
//上架/下架  
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
const boxPublish = (row: { id: any }, opt: string) => {
  let ids: any[] = []
  if (opt == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要上架的订单')
    }
    ids = selection.value
  } else {
    ids = [row.id]
  }
  onShelf(ids).then(() => {
    getTableData()
  })
};
const boxDown = (row: any, opt: string) => {
  let ids: any[] = []
  if (opt == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要下架的订单')
    }
    ids = selection.value
  } else {
    ids = [row.id]
  }
  offShelf(ids).then((res: any) => {
    getTableData()
  })
};

//删除 
let deleteList = ref([])
const isDelete = (row: any, opr: any) => {
  if (opr == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要删除的订单')
    }
    deleteList.value = selection.value
  } else {
    deleteList.value = [row.id]
  }
  param.dialogVisible = true;
};
const activDelete = () => {
  let ids = [...deleteList.value]
  // console.log(ids)
  deletePitch(ids).then((res: any) => {
    getTableData()
  })
  param.dialogVisible = false;
};


//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};


onMounted(() => {
  getTableData()

})

// 功能函数
const formatStateCount = (stateList: any, resList: any) => {
  let total = 0;
  stateList.forEach(item => {
    resList.forEach((obj: { status: number; totalQty: number }) => {
      if (item.id == obj.status) {
        item.num = obj.totalQty
        total += obj.totalQty
      }
    })
  })
 stateList.map(obj => {
    if (obj.id == 0) {
      obj.num = total
    }
  })
  return stateList
};

const formatCityInfo = (list: any) => {
  list.forEach((item: any) => {
    // 城市
    let carryCity = JSON.parse(item.carryCity)
    let returnCity = JSON.parse(item.returnCity)
    let carryCityListString = ''
    let returnCityListString = ''
    if (!carryCity || carryCity.length == 0) return
    carryCity.map((item: any, index: number) => {
      let dos = index == 0 ? '' : '/'
      carryCityListString = carryCityListString + dos + item.cityName
    })
    returnCity.map((item: any, index: number) => {
      let dos = index == 0 ? '' : '/'
      returnCityListString = returnCityListString + dos + item.cityName
    })
    item.carryCityListString = carryCityListString
    item.returnCityListString = returnCityListString
    // 图片
    let mainFileList = JSON.parse(item.mainFileList);
    item.imgUrl = mainFileList.map((item: any) => {
      return item.url
    })[0];
  })

}

//修改提还箱城市
const inputChange = (val1,val2) => {
  param.boxStartCity = val1 // 提箱城市
  param.boxBackCity = val2 //还箱城市
}
const inputBoxConfig = reactive({
  placeholder1:"请输入出发城市",
  placeholder2:"请输入到达城市",
  multiple:true
})

</script>

<style scoped>

.input-wrapper >>> .el-input__wrapper {
  border: none !important;
  box-shadow: none !important;
  height: 28px;
}
</style>